#include "include/MainWindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget* pwgt)
    :QWidget(pwgt), pCommandLinkButton(NULL)
{
    QUiLoader* pUiL = new QUiLoader(this);
    QFile file(":/mainwindow.ui");
    file.open(QFile::ReadOnly);
    QWidget* pwgtForm = pUiL->load(&file);
    file.close();

    if(!pwgtForm)
    {
        qDebug("Unable to load form from file");
        return;
    }

    resize(pwgtForm->size());
    this->pCommandLinkButton = pwgtForm->findChild<QCommandLinkButton*>("commandLinkButton");
    //this->pCommandLinkButton->addAction();

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(pwgtForm);
    setLayout(layout);

    setWindowIcon(QIcon(":/img/apple.png"));

    CreateActions();
    CreateTray();
    ConncetInnerObjects();
}

MainWindow::~MainWindow()
{
}

void MainWindow::CreateActions()
{
    hideAction = new QAction(QIcon(":/img/apple.png"), "Hide", 0);
    connect(hideAction, SIGNAL(triggered()), this, SLOT(hide()));
    quitAction = new QAction(QIcon(":/img/apple.png"), "Quit", 0);
    connect(quitAction, SIGNAL(triggered()), this, SLOT(TrayQuit()));
}

void MainWindow::CreateTray()
{
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(hideAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);

    pTrayIcon = new QSystemTrayIcon(this);
    pTrayIcon->setIcon(QIcon(":/img/apple.png"));
    //pTrayIcon->setContextMenu(trayIconMenu);
    pTrayIcon->show();
}

void MainWindow::ConncetInnerObjects()
{
    connect(this->pCommandLinkButton, SIGNAL(clicked()), hideAction, SIGNAL(triggered()));
    connect(pTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
}

void MainWindow::IconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch(reason)
    {
    case QSystemTrayIcon::DoubleClick:
    {
        qDebug()<<"Double click";
        break;
    }
    case QSystemTrayIcon::Context:
    {
        trayIconMenu->activateWindow();
        trayIconMenu->popup(QCursor::pos());
        qDebug()<<"Context";
        break;
    }
    case QSystemTrayIcon::Trigger:
    {
        this->show();
        qDebug()<<"One click";
        break;
    }
    case QSystemTrayIcon::MiddleClick:
    {
        qDebug()<<"Middle click";
        break;
    }
    default:
        qDebug()<<"Unknown";
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if(pTrayIcon->isVisible())
    {
        hide();
        event->ignore();
    }
}

void MainWindow::TrayQuit()
{
    pTrayIcon->setVisible(false);
    this->close();
}
